<template>
  <div class="dialogBigBox">
    <!-- <callRoom ref="callRoom" /> -->
    <div class="dialogBox">
      <div class="dialogTitle">正在通话
        <i @click="handleHangup"
            class="el-icon-close"
            style="position: absolute; right: 1rem; cursor: pointer"
          ></i>
      </div>
      <div class="audio-call-section-header"></div>

      <!-- <div class="audio-call-section-title">语音通话</div> -->
      <!-- <search-user @callUser="handleCallUser" @cancelCallUser="handleCancelCallUser"></search-user> -->
      <div :class="{ 'audio-conference': true, 'is-show': isShowAudioCall }">
        <div style="font-size: 2.5rem;margin-top: 10%;">{{ inviterName }}</div>
        <div>
          <img
            style="width: 20rem; height: 8rem; margin-left: 5rem"
            src="@assets/images/global/cannected.gif"
          />
        </div>
        <div class="timeText">通话时长：{{ answerh }}:{{ answerm }}:{{ answers }}</div>
        <div  v-if="answeroneminutes > 0 && answeroneminutes < 60" class="timeTextOneminutes">
            通话倒计时：{{ answeroneminutes }}s
          </div>
        <!-- <div class="audio-conference-header">语音通话区域</div> -->
        <div class="audio-conference-list">
          <div
            v-for="userId in meetingUserIdList"
            :key="`audio-${userId}`"
            :class="{
              'user-audio-container': true,
              'is-me': userId === loginUserInfo.userId,
            }"
          >
            <div class="user-status">
              <div
                :class="{
                  'user-audio-status': true,
                  'is-mute': isUserMute(muteAudioUserIdList, userId),
                }"
              ></div>
            </div>
            <div class="audio-item-username">
              aaa{{ userId2User[userId] && userId2User[userId].name }}
            </div>
          </div>
        </div>
        <div style="text-align: right">
          <img
            @click="handleHangup"
            style="
              width: 5rem;
              cursor: pointer;
              position: absolute;
              right: 2rem;
              bottom: 2rem;
            "
            src="../../assets/images/call/guaduan.png"
          />
        </div>
        <!-- <div class="audio-conference-action">
          <el-button class="action-btn" type="success" @click="toggleAudio">{{
            isAudioOn ? "关闭麦克风" : "打开麦克风"
          }}</el-button>

          <el-button class="action-btn" type="danger" @click="handleHangup"
            >挂断</el-button
          >
        </div> -->
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
//import SearchUser from "../search-user";
import { getUserDetailInfoByUserid } from "../../service";
import config from "../../config";
//import callRoom from "@/components/call-room/index.vue";
export default {
  name: "answerService",
  components: {
    //callRoom,
  },
  props: ["inviterName"],
  computed: {
    ...mapState({
      loginUserInfo: (state) => state.loginUserInfo,
      callStatus: (state) => state.callStatus,
      isInviter: (state) => state.isInviter,
      meetingUserIdList: (state) => state.meetingUserIdList,
      muteAudioUserIdList: (state) => state.muteAudioUserIdList,
    }),
  },
  data() {
    return {
      answertimeover: null, //倒计时一分钟的计时器
      answeroneminutes: 60, //倒计时一分钟
      answerh: "00",
      answerm: "00",
      answers: "00",
      answerCallTimer: null, //通话计时器
      isShowAudioCall: false,
      isAudioOn: true,
      userId2User: {},
    };
  },
  mounted() {
    this.queryTime();
    console.log('******************客服通话的mounted******************')
    if (this.callStatus === "connected" && !this.isInviter) {
      this.startMeeting();
      this.updateUserId2UserInfo(this.meetingUserIdList);
    }
  },
  destroyed() {
    console.log('客服呼入弹窗销毁')
    this.$store.commit("updateMuteVideoUserIdList", []);
    this.$store.commit("updateMuteAudioUserIdList", []);
    if (this.callStatus === "connected") {
      this.$trtcCalling.hangup();
      this.$store.commit("updateCallStatus", "idle");
      this.setshowAnswerService(false);
      //this.$router.push("/search-user");
    }
    clearInterval(this.answerCallTimer);//清空通话计时器
    this.answerCallTimer = null;
    clearInterval(this.answertimeover);//清空一分钟倒计时计时器
    this.answertimeover = null;
    this.answeroneminutes = 0;//初始化一分钟计时
    
  },
  watch: {
    callStatus: function (newStatus, oldStatus) {
      // if (newStatus === "connected" || newStatus === "calling") {
      //   //退出房间
      //   this.$refs.callRoom.leaveRoom();
      // } else {
      //   this.$refs.callRoom.createTrtc();
      // }
      // 建立通话连接
      if (newStatus !== oldStatus && newStatus === "connected") {
        this.startMeeting();
        this.updateUserId2UserInfo(this.meetingUserIdList);
      }
    },
    meetingUserIdList: function (newList, oldList) {
      //console.log(newList)
      if (newList !== oldList || newList.length !== oldList.length) {
        this.updateUserId2UserInfo(newList);
        console.log(2);
      }
      // if(this.meetingUserIdList.length<1){
      //   console.log(2)
      //     this.$router.push("/");
      // }
    },
  },
  methods: {
    ...mapMutations([
      "setshowAnswerService", //设置通讯类型
    ]),
    // 计时器
    queryTime() {
      let h = 0;
      let m = 0;
      let s = 0;
      let that = this;
      that.answerCallTimer = setInterval(function () {
        s++;
        if (s >= 60) {
          s = 0;
          that.answers = s < 10 ? "0" + s : s;
          m++;
          if (m >= 60) {
            m = 0;
            that.answerm = m < 10 ? "0" + m : m;
            h++;
            that.answerh = h < 10 ? "0" + h : h;
          } else {
            that.answerm = m < 10 ? "0" + m : m;
          }
        } else {
          that.answers = s < 10 ? "0" + s : s;
        }
        //语音通话，倒计时十五分钟
        if (m == "14" && s == "00") {
          //提示即将挂断
          that.answerendNotify();
        }
      }, 1000);
    },
    //提示通话剩余一分钟
    answerendNotify() {
      this.$message({
        message: "您已通话14分钟，一分钟后将自动挂断",
        type: "warning",
      });
      let oneminutes = 60;
      this.answeroneminutes = 60;
      this.timeover = setInterval(() => {
        oneminutes--;
        this.answeroneminutes = oneminutes;
        if (oneminutes <= 0) {
          clearInterval(this.timeover); //清空计时器
          oneminutes = 0;
          this.handleHangup();//挂断
        }
      }, 1000);
    },
    //取消呼叫
    handleCancelCallBtnClick: function () {
      // 对方刚接受邀请，但进房未成功
      if (this.isAccepted && this.callStatus !== "connected") {
        return;
      }
      this.callUserId = "";
      this.$trtcCalling.hangup();
      this.$store.commit("dissolveMeeting");
      this.$store.commit("updateCallStatus", "idle");
      //this.$router.push("/search-user");
      this.setshowAnswerService(false);
      //this.$emit("cancelCallUser");
    },
    //暂时无用
    handleCallUser: function ({ param }) {
      if (!param) {
        this.$message.error("请输入拨叫号码");
        return;
      }
      this.$trtcCalling.call({
        userID: param,
        type: this.TrtcCalling.CALL_TYPE.AUDIO_CALL,
        timeout: config.CallTimeout,
      });
      this.$store.commit("userJoinMeeting", this.loginUserInfo.userId);
      this.$store.commit("updateCallStatus", "calling");
      this.$store.commit("updateIsInviter", true);
    },
    //暂时无用
    handleCancelCallUser: function () {
      //  if(this.meetingUserIdList.length>1){
      this.$trtcCalling.hangup();
      //}
      //this.$trtcCalling.hangup();
      this.$store.commit("dissolveMeeting");
      this.$store.commit("updateCallStatus", "idle");
      //this.$router.push("/search-user");
      this.setshowAnswerService(false);
    },
    //开启关闭麦克风
    toggleAudio: function () {
      this.isAudioOn = !this.isAudioOn;
      this.$trtcCalling.setMicMute(!this.isAudioOn);
      if (this.isAudioOn) {
        const muteUserList = this.muteAudioUserIdList.filter(
          (userId) => userId !== this.loginUserInfo.userId
        );
        this.$store.commit("updateMuteAudioUserIdList", muteUserList);
      } else {
        const muteUserList = this.muteAudioUserIdList.concat(
          this.loginUserInfo.userId
        );
        console.log(muteUserList);
        this.$store.commit("updateMuteAudioUserIdList", muteUserList);
      }
    },
    //挂断电话
    handleHangup: function () {
      if (this.meetingUserIdList.length > 1) {
        this.$trtcCalling.hangup();
      }
      this.isShowVideoCall = false;
      this.$store.commit("updateCallStatus", "idle");
      this.setshowAnswerService(false);
      //this.$router.push("/search-user");
    },
    isUserMute: function (muteUserList, userId) {
      return muteUserList.indexOf(userId) !== -1;
    },
    startMeeting: function () {
      this.isShowAudioCall = true;
    },
    updateUserId2UserInfo: async function (userIdList) {
      let userId2UserInfo = {};
      let loginUserId = this.loginUserInfo.userId;
      for (let i = 0; i < userIdList.length; i++) {
        const userId = userIdList[i];
        const userInfo = await getUserDetailInfoByUserid(userId);
        userId2UserInfo[userId] = userInfo;
        if (loginUserId === userId) {
          userId2UserInfo[userId].name += "(me)";
        }
      }
      this.userId2User = {
        ...this.userId2User,
        ...userId2UserInfo,
      };
    },
    goto: function (path) {
      this.$router.push(path);
    },
  },
};
</script>

<style scoped>
.audio-call-section {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: 30%;
  /* padding-top: 50px;
  width: 800px;
  margin: 0 auto; */
}
.audio-call-section-header {
  font-size: 24px;
}
.audio-call-section-title {
  margin-top: 30px;
  font-size: 20px;
}
.audio-conference {
  display: none;
  margin-top: 20px;
}
.audio-conference.is-show {
  display: block;
}

.audio-conference-list {
  display: flex;
  flex-direction: row;
  margin-top: 10px;
  justify-content: center;
  position: absolute;
  left: -300rem;
}

.user-audio-container {
  background-color: #333;
  position: relative;
  text-align: left;
  width: 360px;
  height: 240px;
  margin-right: 10px;
  background: black;
}

.audio-conference-action {
  margin-top: 10px;
}

.user-audio-status {
  position: absolute;
  right: 20px;
  bottom: 20px;
  width: 22px;
  height: 27px;
  z-index: 10;
  background-image: url("../../assets/mic-on.png");
  background-size: cover;
}

.audio-item-avatar-wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  width: 80px;
  height: 80px;
  z-index: 20;
}

.audio-item-avatar-wrapper img {
  width: 80px;
  height: 80px;
}

.user-audio-status.is-mute {
  background-image: url("../../assets/mic-off.png");
}

.audio-item-username {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 10;
  color: #ffffff;
}
.sectionBox {
  width: 55rem;
  height: 20rem;
  background-color: red;
}
.dialogBigBox {
  z-index: 999;
  width: 100%;
  height: 100%;
  background-color: #0000006b;
  position: absolute;
  left: 0rem;
  top: 0rem;
}
.dialogBox {
  width: 40rem;
  height: 50%;
  background-color: white;
  position: absolute;
  left: 30rem;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 0.5rem;
  padding-bottom: 3rem;
}
.dialogTitle {
  padding: 0.6rem 1rem 0rem;
  text-align: left;
  font-size: 1.5rem;
}
.timeText {
  color: black;
  text-align: center;
  font-size: 1.3rem;
  margin-top: -1rem;
}
.timeTextOneminutes {
  color: black;
  text-align: center;
  font-size: 1.3rem;
}
</style>
